package com.hssy.wululuaplan.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hssy.wululuaplan.common.ExceptionCodeEnum;
import com.hssy.wululuaplan.entity.SysUser;
import com.hssy.wululuaplan.entity.SysUserToken;
import com.hssy.wululuaplan.exception.CustomException;
import com.hssy.wululuaplan.form.LoginParam;
import com.hssy.wululuaplan.mapper.SysUserMapper;
import com.hssy.wululuaplan.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

/**
 * 登录处理业务类
 * @since 2025/6/18 14:00
 * @author Mr.Hongtao
 */
@Slf4j
@Service
public class LoginService {

    private static final String SALT_PWD = "Oklabubu@1q~Az(Pps";

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysUserTokenService sysUserTokenService;


    public String login(LoginParam loginParam) {
        String username = loginParam.getUsername();
        String password = loginParam.getPassword();
        password = DigestUtils.md5Hex(password + SALT_PWD);
        SysUser sysUser = sysUserMapper.selectOne(Wrappers.<SysUser>lambdaQuery()
                .eq(SysUser::getUsername, username)
                .eq(SysUser::getPassword, password));
        if (sysUser == null) {
            throw new CustomException(ExceptionCodeEnum.USERNAME_PASSWORD_ERROR);
        }

        String token = JwtUtils.createToken(sysUser.getId());

        // 查询是否登录过
        SysUserToken sysUserToken = sysUserTokenService.getOne(Wrappers.<SysUserToken>lambdaQuery()
                .eq(SysUserToken::getUserId, sysUser.getId())
                .last("limit 1"));
        if (sysUserToken == null) {
            sysUserToken = new SysUserToken();
            sysUserToken.setUserId(sysUser.getId());
            sysUserToken.setToken(token);
            sysUserToken.setExpireDate(DateUtil.offsetDay(new Date(), 1));
        }else {
            sysUserToken.setToken(token);
            sysUserToken.setExpireDate(DateUtil.offsetDay(new Date(), 1));
        }
        sysUserTokenService.saveOrUpdate(sysUserToken);
        log.info("登录成功");
        return token;
    }

    public static void main(String[] args) {
        System.out.println("当前时间" + DateUtil.now());
        System.out.println();
    }



    public void logout(String token) {
        Map<String, Object> map = JwtUtils.checkToken(token);
        if (map == null) {
            return;
        }

        SysUserToken sysUserToken = sysUserTokenService.getOne(Wrappers.<SysUserToken>lambdaQuery()
                .eq(SysUserToken::getToken, token));
        if (sysUserToken != null) {
            sysUserToken.setExpireDate(new Date());
            sysUserTokenService.updateById(sysUserToken);
        }

    }
}
